﻿using System;
using System.Collections.Generic;
using System.Web;
using Core.Authenticated;
using Core.Library;
using DataObject;
using DataObject.Article;
using DataObject.Category;
using System.Web.UI.WebControls;

namespace CMS.Controls.Article
{
    public partial class CreateOrEdit : AuthenticatedControl
    {
        protected int ArticleId;
        protected string ReturnUrl;

        protected void Page_Load(object sender, EventArgs e)
        {
            ArticleId   = Utils.GetIdFromRequestString(Utils.ArticleId, 0);
            ReturnUrl   = Utils.GetIdFromRequestString(Utils.ReturnUrl, string.Empty);
            
            if (!IsPostBack)
            {
                InitEditor();

                ltTitle.Text = ArticleId > 0 ? "Sửa bài viết" : "Tạo mới bài viết";

                ListTreeCategory();

                if (ArticleId > 0)
                    BindArticle(ArticleId);
            }
        }

        #region Init Editor

        private void InitEditor()
        {
            /*
            txtSapo.config.language = "vi-VN";
            txtSapo.config.toolbar = new object[]
            {
                new object[] { "Source", "-", "Maximize", "-", "Templates", "Table", "-", "Bold", "Italic", "-", "NumberedList", "BulletedList"}
            };

            txtBody.config.language = "vi-VN";
            txtBody.config.toolbar = new object[]
			{
				new object[] { "Source", "Preview", "Templates" },
				new object[] { "Cut", "Copy", "Paste", "PasteText", "PasteFromWord", "-", "Print", "SpellChecker", "Scayt" },
				new object[] { "Undo", "Redo", "-", "Find", "Replace", "-", "SelectAll", "RemoveFormat" },
				new object[] { "Bold", "Italic", "Underline", "Strike", "-", "Subscript", "Superscript" },
				new object[] { "NumberedList", "BulletedList", "-", "Outdent", "Indent", "Blockquote", "CreateDiv" },
                "/",
				new object[] { "JustifyLeft", "JustifyCenter", "JustifyRight", "JustifyBlock" },
				new object[] { "Link", "Unlink", "Anchor" },
				new object[] { "Image", "Table", "HorizontalRule", "Smiley", "SpecialChar", "PageBreak" },
				new object[] { "Styles", "Format", "Font", "FontSize" },
				new object[] { "TextColor", "BGColor" },
				new object[] { "Maximize", "ShowBlocks" }
			};
            */
        }

        #endregion

        private void ListTreeCategory()
        {
            var categories = new List<CategoryObject>();
            CategoryController.GetListTree(categories, (int)CategoryType.Article, 0, Constants.PARENT_ROOT);

            if (categories.Count > 0)
            {
                ddlCategory.DataSource = categories;
                ddlCategory.DataBind();
                ddlCategory.Items.Insert(0, new ListItem("-- Chuyên mục --", "0"));
            }
        }

        private void BindArticle(int id)
        {
            var o = ArticleController.Article_GetById(id);
            if (o == null) return;

            ddlCategory.SelectedValue   = o.CategoryId.ToString();
            txtTitle.Text               = o.Title;
            txtSapo.Text                = o.Sapo;
            txtBody.Text                = o.Body;
            txtSource.Text              = o.Source;
            txtImage.Text               = o.ImgAvatar;
            txtPublishOn.Text           = DateTimeFunctions.FormatDateVietNam(o.PublishOn);
            txtTime.Text                = DateTimeFunctions.FormatTimeVietNam(o.PublishOn);

            // Tiêu điểm
            if (StatusHelper.IsChecked(o.Status, StatusHelper.IsHighlight))
                cbHighlight.Checked = true;

            // Trạng thái bài viết
            if (StatusHelper.IsChecked(o.Status, StatusHelper.IsWaitingForPublish))
                ddlStatus.SelectedValue = StatusHelper.IsWaitingForPublish.ToString();
            else if ((StatusHelper.IsChecked(o.Status, StatusHelper.IsPublished)))
                ddlStatus.SelectedValue = StatusHelper.IsPublished.ToString();
        }

        protected void BtnSave(object sender, EventArgs e)
        {
            ArticleObject o;
            
            var publishOn = DateTimeFunctions.ValidDateTime(txtPublishOn.Text, txtTime.Text);
            var status    = ConvertUtility.ToInt32(ddlStatus.SelectedValue);

            if (cbHighlight.Checked)
                status = status + StatusHelper.IsHighlight;
                                   
            if (ArticleId > 0)
            {
                o = ArticleController.Article_GetById(ArticleId);
                o.CategoryId       = ConvertUtility.ToInt32(ddlCategory.SelectedValue);
                o.ArticleId        = ArticleId;
                o.Title            = txtTitle.Text;
                o.Sapo             = txtSapo.Text;
                o.Body             = txtBody.Text;
                o.Source           = txtSource.Text;
                o.ImgAvatar        = txtImage.Text;
                o.PublishOn        = publishOn;
                o.Status           = status;
                o.EditedBy         = CurrentUser.AdminUserId.ToString();
                o.ApprovedBy       = CurrentUser.AdminUserId.ToString();

                ArticleController.Article_Update(o);
            }
            else
            {
                o = new ArticleObject();
                o.CategoryId       = ConvertUtility.ToInt32(ddlCategory.SelectedValue);
                o.Title            = txtTitle.Text;
                o.Sapo             = txtSapo.Text;
                o.Body             = txtBody.Text;
                o.Source           = txtSource.Text;
                o.ImgAvatar        = txtImage.Text;
                o.PublishOn        = publishOn;
                o.Status           = status;
                o.CreatedBy        = CurrentUser.AdminUserId.ToString();

                ArticleController.Article_Create(o);                
            }

            Response.Redirect(!string.IsNullOrEmpty(ReturnUrl) ? HttpUtility.HtmlDecode(ReturnUrl) : UrlHelpers.ListArticle);
        }        
    }
}